package controller

import (
	"fmt"
	"os"
	"strings"

	"git-todo/service"
	"git-todo/view"
)

// CLIController 命令行控制器
type CLIController struct {
	todoService *service.TodoService
	view        *view.TodoView
}

// NewCLIController 创建新的CLI控制器
func NewCLIController(todoService *service.TodoService, view *view.TodoView) *CLIController {
	return &CLIController{
		todoService: todoService,
		view:        view,
	}
}

// HandleCommand 处理命令行参数
func (c *CLIController) HandleCommand(args []string) {
	if len(args) < 2 {
		c.view.ShowHelp()
		return
	}

	command := args[1]

	switch command {
	case "add":
		c.handleAdd(args[2:])
	case "list":
		c.handleList()
	case "done":
		c.handleDone(args[2:])
	case "help", "-h", "--help":
		c.view.ShowHelp()
	case "version", "-v", "--version":
		c.view.ShowVersion()
	default:
		c.view.ShowError(fmt.Sprintf("未知命令: %s", command))
		c.view.ShowHelp()
	}
}

// handleAdd 处理添加待办事项命令
func (c *CLIController) handleAdd(args []string) {
	if len(args) == 0 {
		c.view.ShowError("请提供待办事项描述")
		c.view.ShowUsage("add", "git todo add <待办事项描述>")
		return
	}

	// 将所有参数连接为描述
	description := strings.Join(args, " ")

	if err := c.todoService.AddTodo(description); err != nil {
		c.view.ShowError(err.Error())
		return
	}

	// 获取当前分支信息用于显示
	branch, err := c.todoService.GetCurrentBranch()
	if err != nil {
		branch = "unknown"
	}

	c.view.ShowAddSuccess(description, branch)
}

// handleList 处理列出待办事项命令
func (c *CLIController) handleList() {
	todos, err := c.todoService.ListTodos()
	if err != nil {
		c.view.ShowError(err.Error())
		return
	}

	// 获取当前分支信息
	branch, err := c.todoService.GetCurrentBranch()
	if err != nil {
		branch = "unknown"
	}

	c.view.ShowTodoList(todos, branch)
}

// handleDone 处理标记完成命令
func (c *CLIController) handleDone(args []string) {
	if len(args) == 0 {
		c.view.ShowError("请提供待办事项的ID或描述")
		c.view.ShowUsage("done", "git todo done <ID或描述>")
		return
	}

	// 将所有参数连接为标识符
	identifier := strings.Join(args, " ")

	if err := c.todoService.CompleteTodo(identifier); err != nil {
		c.view.ShowError(err.Error())
		return
	}

	// 获取当前分支信息用于显示
	branch, err := c.todoService.GetCurrentBranch()
	if err != nil {
		branch = "unknown"
	}

	c.view.ShowCompleteSuccess(identifier, branch)
}

// Run 运行CLI应用程序
func (c *CLIController) Run() {
	c.HandleCommand(os.Args)
}
